package cn.itcast.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Menu;
import cn.itcast.pojo.UserInfo;
import cn.itcast.service.MenuService;
import cn.itcast.vo.MenuListVo;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
@Slf4j
public class MenuController {
    @Reference
    private MenuService menuService;

    @PreAuthorize("hasAuthority('MENU_EDIT')")
    @PutMapping
    public ResponseEntity<Result> edit( @RequestParam("permissionIds") List<Integer> permissionIds,
                                        @RequestBody Menu menu) {
        Result result = new Result();
        try {
            Boolean flag = menuService.edit(permissionIds,menu);
            if (flag) {
                result.setFlag(true);
                result.setMessage(MessageConstant.EDIT_MENU_SUCCESS);
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            log.error(MessageConstant.EDIT_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.EDIT_MENU_FAIL);
        return ResponseEntity.ok(result);
    }


    @PreAuthorize("hasAuthority('MENU_DELETE')")
    @DeleteMapping("/{id}")
    public ResponseEntity<Result> delete(@PathVariable Integer id) {
        Result result = new Result();
        try {
            Boolean flag = menuService.delete(id);
            if (flag) {
                result.setFlag(true);
                result.setMessage(MessageConstant.DELETE_MENU_SUCCESS);
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            log.error(MessageConstant.DELETE_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.DELETE_MENU_FAIL);
        return ResponseEntity.ok(result);
    }


    /**
     *
     *
     * @return
     */
    @PreAuthorize("hasAuthority('MENU_ADD')")
    @PostMapping
    public ResponseEntity<Result> saveMenu( @RequestParam("permissionIds") List<Integer> permissionIds,
                                            @RequestBody Menu menu) {
        Result result = new Result();
        try {
            Boolean flag = menuService.save(permissionIds,menu);
            if (flag) {
                result.setFlag(true);
                result.setMessage(MessageConstant.ADD_MENU_SUCCESS);
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            log.error(MessageConstant.ADD_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.ADD_MENU_FAIL);
        return ResponseEntity.ok(result);
    }

    /**
     *
     *
     * @param currentPage
     * @param pageSize
     * @param
     * @return
     */
    @PreAuthorize("hasAuthority('MENU_QUERY')")
    @GetMapping("/page")
    public ResponseEntity<Result> findByPage(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Result result = new Result();
        try {
            PageResult pageResult = menuService.findByPage(currentPage, pageSize);
            if (ObjectUtil.isNotEmpty(pageResult)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_MENU_SUCCESS);
                result.setData(pageResult);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_MENU_FAIL);
        return ResponseEntity.ok(result);
    }

    @GetMapping
    public ResponseEntity<Result> findAll() {
        Result result = new Result();
        try {
            List<Menu> menuList = menuService.findAll();
            if (ObjectUtil.isNotEmpty(menuList)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_MENU_SUCCESS);
                result.setData(menuList);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_MENU_FAIL);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Result> findById(@PathVariable Integer id) {
        Result result = new Result();
        try {
            Menu menu = menuService.findById(id);
            if (ObjectUtil.isNotEmpty(menu)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_MENU_SUCCESS);
                result.setData(menu);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_MENU_FAIL);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/{menuId}/permissions")
    public ResponseEntity<Result> findPermissionIdsByMenuId(@PathVariable Integer menuId) {
        Result result = new Result();
        try {
            List<Integer> permissionIds = menuService.findPermissionIdsByMenuId(menuId);
            if (CollUtil.isNotEmpty(permissionIds)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_MENU_SUCCESS);
                result.setData(permissionIds);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_MENU_FAIL);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/findMenuByUserId")
    public ResponseEntity<Result> findMenuByUserId(){
        Result result = new Result();
        try {
            UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<MenuListVo> menuListVo = menuService.findMenuByUserId(userInfo.getId());
            if (CollUtil.isNotEmpty(menuListVo)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_MENU_SUCCESS);
                result.setData(menuListVo);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_MENU_FAIL);
        return ResponseEntity.ok(result);
    }
}
